package com.mars.sso.server.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.mars.base.common.exception.AppException;
import com.mars.base.common.utils.CookieUtils;
import com.mars.base.common.utils.RandomUitl;
import com.mars.base.common.utils.web.ResponseResult;
import com.mars.base.web.BaseController;
import com.mars.component.redis.JedisClient;
import com.mars.manager.user.entity.User;
import com.mars.manager.user.service.UserService;
import com.mars.sso.server.contants.Config;

@RestController
public class SSOController extends BaseController {

	@Autowired
	private UserService userService;

	@Autowired
	private JedisClient jedisClient;

	@PostMapping(value = "/login")
	public Object login(String account, String password) {
		try {

			User user = this.userService.getAccount(account);
			if (null != user) {
				boolean validatePassword = this.userService.validatePassword(user.getPassword(), password, user.getSalt());
				if (validatePassword) {
					if (user.getStatus() == 2) {
						return ResponseResult.build(false, "该帐号已被禁用，请联系管理员");
					}
					// 清空密码
					user.setPassword(null);

					// 生成用户会话Token
					String token = RandomUitl.uuid();

					// 设置用户会话Token到Cookie中并设定过期时间
					CookieUtils.setCookie(this.request, this.response, Config.SSO_VT, token, Config.TIMEOUT);

					String redisKey = Config.REDIS_KEY_SSO_TOKEN_KEY + ":" + token;

					// 将用户信息保存在Redis中
					this.jedisClient.set(redisKey, JSON.toJSONString(user));
					// 设置TOKENG过期时间
					this.jedisClient.expire(redisKey, Config.TIMEOUT);

					return ResponseResult.build(true, "登录成功", user);
				} else {
					return ResponseResult.build(false, "密码错误");
				}

			} else {
				return ResponseResult.build(false, "用户不存在");
			}

		} catch (AppException e) {
			return ResponseResult.build(false, "登录发生异常，请联系管理员");
		}
	}

	@GetMapping("/validate_service")
	public Object validate_service(String vt) {
		String userStr = this.jedisClient.get(Config.REDIS_KEY_SSO_TOKEN_KEY + ":" + vt);
		return JSON.parseObject(userStr, User.class);
	}

}
